<?php
/**
 * author    tangxiaowen
 * mail:     846506584@qq.com
 * Date:     2019/3/22 11:33
 * describe: 统计类.
 */

namespace app\admin\controller;

use think\Request;
use think\Db;

class Sum extends Common
{
    /**
     * 主页统计
     */
    public function indexSum()
    {
        $page = 0;
        $limit = 15;
        $timeData = $this->getTimeData($page, $limit, '');

        //获取当前请求显示页的时间参数
        $timeArr = array_slice($timeData, $page, $limit);

        //处理时间参数并查询相关所有待数据
        $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

        //获取用户注册数
        $usWhere['RegTime'] = $time;
        $userData = db('mem_info')->where($usWhere)->field(['RegTime,ID'])->select();

        //申请订单数
        $sqWhere['ApplyTime'] = $time;
        $sqOrderData = db('loans_applylist')->where($sqWhere)->field(['ID,ApplyTime,ApplyMoney'])->select();

        //放款订单
        $fkWhere['OpenTime'] = $time;
        $fkOrderData = db('loans_applylist')->where($fkWhere)->field(['ID,OpenTime,AdoptMoney'])->select();

        //还款订单数
        $hkWhere['SjFkTime'] = $time;
        $hkOrderData = db('loans_applylist')->alias('a')
            ->join('xb_loans_hklist h', 'a.ID = h.ApplyID')
            ->where($hkWhere)
            ->field('a.ID,SUM(h.TotalMoney) as sumMoney,a.SjFkTime')
            ->group('a.ID')
            ->select();

        $yhNums = []; //用户注册数
        $sqNums = []; //申请订单数
        $fkNums = []; //放款订单数
        $hkNums = []; //还款订单数

        $sqMoneys = []; //申请金额
        $fkMoneys = []; //放款金额
        $hkMoneys = []; //还款金额

        //处理数据
        for ($i = 0; $i < count($timeArr); ++$i) {
            //每日日期区间
            $startTime = strtotime($timeArr[$i]);
            $endTime = $startTime + 86400;

            $yhNum = 0;
            foreach ($userData as $k => $v) {
                if (strtotime($v['RegTime']) >= $startTime && strtotime($v['RegTime']) < $endTime) {
                    ++$yhNum;
                }
            }

            $sqNum = 0;
            $sqMoney = 0;
            foreach ($sqOrderData as $k => $v) {
                if (strtotime($v['ApplyTime']) >= $startTime && strtotime($v['ApplyTime']) < $endTime) {
                    ++$sqNum;
                    $sqMoney += $v['ApplyMoney'];
                }
            }

            $fkNum = 0;
            $fkMoney = 0;
            foreach ($fkOrderData as $k => $v) {
                if (strtotime($v['OpenTime']) >= $startTime && strtotime($v['OpenTime']) < $endTime) {
                    ++$fkNum;
                    $fkMoney += $v['AdoptMoney'];
                }
            }

            $hkNum = 0;
            $hkMoney = 0;
            foreach ($hkOrderData as $k => $v) {
                if (strtotime($v['SjFkTime']) >= $startTime && strtotime($v['SjFkTime']) < $endTime) {
                    ++$hkNum;
                    $hkMoney += $v['sumMoney'];
                }
            }

            array_push($yhNums, $yhNum);
            array_push($sqNums, $sqNum);
            array_push($fkNums, $fkNum);
            array_push($hkNums, $hkNum);

            array_push($sqMoneys, $sqMoney);
            array_push($fkMoneys, $fkMoney);
            array_push($hkMoneys, $hkMoney);
        }

        $temp = [
            'time' => array_reverse($timeArr),
            'num' => [
                ['name' => '注册人数', 'data' => array_reverse($yhNums)],
                ['name' => '申请单数', 'data' => array_reverse($sqNums)],
                ['name' => '放款单数', 'data' => array_reverse($fkNums)],
                ['name' => '还款单数', 'data' => array_reverse($hkNums)],
            ],
            'money' => [
                ['name' => '申请金额', 'data' => array_reverse($sqMoneys)],
                ['name' => '放款金额', 'data' => array_reverse($fkMoneys)],
                ['name' => '还款金额', 'data' => array_reverse($hkMoneys)],
            ],
        ];

        return json(['code' => 200, 'msg' => '请求成功', 'data' => $temp]);
    }

    /**
     * 逾期统计
     */
    public function overdue()
    {
        if (request()->isAjax()) {
            //获取请求的页数 条数 时间筛选参数
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('YyFkTime2', 'not null')->order('YyFkTime2 ASC')->value('YyFkTime2');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }
            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理时间参数并查询相关所有待数据
                $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

                //获取主订单数据
                $orWhere['a.YyFkTime2'] = $time;
                $orWhere['a.LoanStatus'] = ['in', '2,3'];
                $orderData = db('loans_applylist')->alias('a')
                    ->join('xb_loans_hklist h', 'a.ID = h.ApplyID', 'LEFT')
                    ->where($orWhere)
                    ->group('a.ID')
                    ->field('a.ID,a.YyFkTime2 as YyFkTime,a.LoanStatus,a.user_type,a.app_type,h.HkTime')
                    ->select();

                //获取续期订单数据
                $xqWhere['x.YyFkTime'] = $time;
                $xqWhere['a.LoanStatus'] = ['in', '2,3'];
                $xqOrderData = db('loans_xjapplylist')->alias('x')
                    ->join('xb_loans_applylist a', 'x.AppID = a.ID')
                    ->join('xb_loans_hklist h', 'a.ID = h.ApplyID', 'LEFT')
                    ->group('x.ID')
                    ->where($xqWhere)
                    ->field('a.ID,a.LoanStatus,a.user_type,a.app_type,x.CreateTime,x.YyFkTime,h.HkTime,x.ID as xID')
                    ->select();
                $data = array_merge($orderData, $xqOrderData);
                $orderObj = new Order();

                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $yhNum = 0; //应还单数
                    $yhNums = 0; //已还单数
                    $yqNum = 0; //逾期单数
                    $yqYhNum = 0; //逾期已还单数

                    $xkYqNum = 0; //新客逾期单数
                    $xkYhNum = 0; //新客已还单数

                    $lkYqNum = 0; //老客逾期单数
                    $lkYhNum = 0; //老客已换单数

                    $yq13Num = 0; //逾期1-3天单数
                    $yh13Num = 0; //逾期1-3天已还单数

                    $yq47Num = 0; //逾期4-7天单数
                    $yh47Num = 0; //逾期4-7天已还单数

                    $yq815Num = 0; //逾期8-15天单数
                    $yh815Num = 0; //逾期8-15已还单数

                    $yq15Num = 0; //逾期15天单数
                    $yh15Num = 0; //逾期15天已还单数

                    foreach ($data as $k => $v) {
                        if (strtotime($v['YyFkTime']) >= $startTime && strtotime($v['YyFkTime']) < $endTime) {
                            ++$yhNum;
                            //检测订单是否逾期
                            $isOrderOverdue = $orderObj->isOrderOverdue($v, false);
                            //所有逾期
                            if ($isOrderOverdue) {
                                if ($v['LoanStatus'] == 3) {
                                    ++$yhNums;
                                    //已还订单中检测是否是逾期已还
                                    if (strtotime($v['HkTime']) > strtotime($v['YyFkTime'].' 23:59:59')) {
                                        ++$yqYhNum;

                                        //检测是否新客
                                        if ($v['user_type'] == 1) {
                                            ++$xkYhNum;
                                        }
                                        //检测是否老客
                                        if ($v['user_type'] == 2) {
                                            ++$lkYhNum;
                                        }
                                        //逾期1-3天
                                        if ($isOrderOverdue > 0 && $isOrderOverdue <= 3) {
                                            ++$yh13Num;
                                        }
                                        //逾期4-7天
                                        if ($isOrderOverdue > 3 && $isOrderOverdue <= 7) {
                                            ++$yh47Num;
                                        }
                                        //逾期8-15天
                                        if ($isOrderOverdue > 7 && $isOrderOverdue <= 15) {
                                            ++$yh815Num;
                                        }
                                        //逾期大于15天
                                        if ($isOrderOverdue > 15) {
                                            ++$yh15Num;
                                        }
                                    }
                                }
                                if ($v['LoanStatus'] != 3) {//逾期未还
                                    ++$yqNum;
                                    //检测是否新客
                                    if ($v['user_type'] == 1) {
                                        ++$xkYqNum;
                                        //检测新客是否已还
                                        if ($v['LoanStatus'] == 3) {
                                            ++$xkYhNum;
                                        }
                                    }
                                    //检测是否老客
                                    if ($v['user_type'] == 2) {
                                        ++$lkYqNum;
                                        //检测是否为老客 是+1
                                        if ($v['LoanStatus'] == 3) {
                                            ++$lkYhNum;
                                        }
                                    }
                                    //逾期1-3天
                                    if ($isOrderOverdue > 0 && $isOrderOverdue <= 3) {
                                        ++$yq13Num;
                                        if ($v['LoanStatus'] == 3) {
                                            ++$yh13Num;
                                        }
                                    }
                                    //逾期4-7天
                                    if ($isOrderOverdue > 3 && $isOrderOverdue <= 7) {
                                        ++$yq47Num;
                                        if ($v['LoanStatus'] == 3) {
                                            ++$yh47Num;
                                        }
                                    }
                                    //逾期8-15天
                                    if ($isOrderOverdue > 7 && $isOrderOverdue <= 15) {
                                        ++$yq815Num;
                                        if ($v['LoanStatus'] == 3) {
                                            ++$yh815Num;
                                        }
                                    }
                                    //逾期大于15天
                                    if ($isOrderOverdue > 15) {
                                        ++$yq15Num;
                                        if ($v['LoanStatus'] == 3) {
                                            ++$yh15Num;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //追加数据
                    $tempData[] = [
                        'time' => $timeArr[$i], //日期

                        'yhNum' => $yhNum,
                        'yhNums' => $yhNums,
                        'yqNum' => $yqNum,
                        'yqYhNum' => $yqYhNum,
                        'yqHkLv' => (($yqNum != 0) ? (sprintf('%.2f', ($yqYhNum / $yqNum) * 100)) : 0).'%', //逾期回款率

                        'xkYqNum' => $xkYqNum,
                        'xkYhNum' => $xkYhNum,
                        'xkHkLv' => (($xkYqNum != 0) ? (sprintf('%.2f', ($xkYhNum / $xkYqNum) * 100)) : 0).'%', //回款率

                        'lkYqNum' => $lkYqNum,
                        'lkYhNum' => $lkYhNum,
                        'lkHkLv' => (($lkYqNum != 0) ? (sprintf('%.2f', ($lkYhNum / $lkYqNum) * 100)) : 0).'%', //回款率

                        'yq13Num' => $yq13Num,
                        'yh13Num' => $yh13Num,
                        'yq13HkLv' => (($yq13Num != 0) ? (sprintf('%.2f', ($yh13Num / $yq13Num) * 100)) : 0).'%', //回款率

                        'yq47Num' => $yq47Num,
                        'yh47Num' => $yh47Num,
                        'yq47HkLv' => (($yq47Num != 0) ? (sprintf('%.2f', ($yh47Num / $yq47Num) * 100)) : 0).'%', //回款率

                        'yq815Num' => $yq815Num,
                        'yh815Num' => $yh815Num,
                        'yq845HkLv' => (($yq815Num != 0) ? (sprintf('%.2f', ($yh815Num / $yq815Num) * 100)) : 0).'%', //回款率

                        'yq15Num' => $yq15Num,
                        'yh15Num' => $yh15Num,
                        'yq15HkLv' => (($yq15Num != 0) ? (sprintf('%.2f', ($yh15Num / $yq15Num) * 100)) : 0).'%', //回款率
                    ];
                }
            }

            //总条数
            $count = count($timeData);

            return json(['code' => 0, 'msg' => '添加成功', 'count' => $count, 'data' => $tempData]);
        }

        return view();
    }

    /**
     * 渠道逾期
     */
    public function overdueChannel()
    {
        $time = ['between', input('time').','.input('time').' 23:59:59'];

        //获取主订单数据
        $orWhere['a.YyFkTime'] = $time;
        $orWhere['a.LoanStatus'] = ['in', '2,3'];
        $orderData = db('loans_applylist')->alias('a')
            ->join('xb_mem_info m', 'a.UserID = m.ID', 'LEFT')
            ->join('xb_tg_admin t', 'm.TgadminID = t.ID', 'LEFT')
            ->where($orWhere)
            ->field('a.ID,a.YyFkTime,a.LoanStatus,a.user_type,a.app_type,t.Name')
            ->select();

        //获取续期订单数据
        $xqWhere['x.YyFkTime'] = $time;
        $xqWhere['a.LoanStatus'] = ['in', '2,3'];
        $xqOrderData = db('loans_xjapplylist')->alias('x')
            ->join('xb_loans_applylist a', 'x.AppID = a.ID', 'LEFT')
            ->join('xb_mem_info m', 'a.UserID = m.ID', 'LEFT')
            ->join('xb_tg_admin t', 'm.TgadminID = t.ID', 'LEFT')
            ->where($xqWhere)
            ->field('a.ID,a.LoanStatus,a.user_type,a.app_type,x.YyFkTime,t.Name')
            ->select();

        //主订单数据与续期订单数据合并并获取所有渠道名称(去重后的)
        $data = array_merge($orderData, $xqOrderData);
        $channel = [];
        foreach (array_column($data, 'Name') as $K => $v) {
            if (!in_array($v, $channel)) {
                array_push($channel, $v);
            }
        }

        $orderObj = new Order();
        $tempData = [];
        for ($i = 0; $i < count($channel); ++$i) {
            $yhNum = 0; //应还单数
            $yhNums = 0; //已还单数
            $yqNum = 0; //逾期单数
            $yqYhNum = 0; //逾期已还单数

            $xkYqNum = 0; //新客逾期单数
            $xkYhNum = 0; //新客已还单数

            $lkYqNum = 0; //老客逾期单数
            $lkYhNum = 0; //老客已换单数

            $yq13Num = 0; //逾期1-3天单数
            $yh13Num = 0; //逾期1-3天已还单数

            $yq47Num = 0; //逾期4-7天单数
            $yh47Num = 0; //逾期4-7天已还单数

            $yq815Num = 0; //逾期8-15天单数
            $yh815Num = 0; //逾期8-15已还单数

            $yq15Num = 0; //逾期15天单数
            $yh15Num = 0; //逾期15天已还单数

            foreach ($data as $k => $v) {
                if ($channel[$i] == $v['Name']) {
                    ++$yhNum;
                    if ($v['LoanStatus'] == 3) {
                        ++$yhNums;
                    }
                    //检测订单是否逾期
                    $isOrderOverdue = $orderObj->isOrderOverdue($v, false);
                    //所有逾期
                    if ($isOrderOverdue) {
                        if ($v['LoanStatus'] != 3) {
                            ++$yqNum;
                        }
                        if ($v['LoanStatus'] == 3) {
                            ++$yqYhNum;
                        }
                        //检测是否新客
                        if ($v['user_type'] == 1) {
                            ++$xkYqNum;
                            //检测新客是否已还
                            if ($v['LoanStatus'] == 3) {
                                ++$xkYhNum;
                            }
                        }
                        //检测是否老客
                        if ($v['user_type'] == 2) {
                            ++$lkYqNum;
                            //检测是否为老客 是+1
                            if ($v['LoanStatus'] == 3) {
                                ++$lkYhNum;
                            }
                        }
                    }
                    //逾期1-3天
                    if ($isOrderOverdue > 0 && $isOrderOverdue < 3) {
                        ++$yq13Num;
                        if ($v['LoanStatus'] == 3) {
                            ++$yh13Num;
                        }
                    }
                    //逾期4-7天
                    if ($isOrderOverdue > 3 && $isOrderOverdue < 7) {
                        ++$yq47Num;
                        if ($v['LoanStatus'] == 3) {
                            ++$yh47Num;
                        }
                    }
                    //逾期8-15天
                    if ($isOrderOverdue > 8 && $isOrderOverdue < 15) {
                        ++$yq815Num;
                        if ($v['LoanStatus'] == 3) {
                            ++$yh815Num;
                        }
                    }
                    //逾期大于15天
                    if ($isOrderOverdue > 15) {
                        ++$yq15Num;
                        if ($v['LoanStatus'] == 3) {
                            ++$yh15Num;
                        }
                    }
                }
            }

            //追加数据
            $tempData[] = [
                'name' => $channel[$i], //日期

                'yhNum' => $yhNum,
                'yhNums' => $yhNums,
                'yqNum' => $yqNum,
                'yqYhNum' => $yqYhNum,
                'yqHkLv' => (($yqNum != 0) ? (sprintf('%.2f', ($yqYhNum / $yqNum) * 100)) : 0).'%', //逾期回款率

                'xkYqNum' => $xkYqNum,
                'xkYhNum' => $xkYhNum,
                'xkHkLv' => (($xkYqNum != 0) ? (sprintf('%.2f', ($xkYhNum / $xkYqNum) * 100)) : 0).'%', //回款率

                'lkYqNum' => $lkYqNum,
                'lkYhNum' => $lkYhNum,
                'lkHkLv' => (($lkYqNum != 0) ? (sprintf('%.2f', ($lkYhNum / $lkYqNum) * 100)) : 0).'%', //回款率

                'yq13Num' => $yq13Num,
                'yh13Num' => $yh13Num,
                'yq13HkLv' => (($yq13Num != 0) ? (sprintf('%.2f', ($yh13Num / $yq13Num) * 100)) : 0).'%', //回款率

                'yq47Num' => $yq47Num,
                'yh47Num' => $yh47Num,
                'yq47HkLv' => (($yq47Num != 0) ? (sprintf('%.2f', ($yh47Num / $yq47Num) * 100)) : 0).'%', //回款率

                'yq815Num' => $yq815Num,
                'yh815Num' => $yh815Num,
                'yq845HkLv' => (($yq815Num != 0) ? (sprintf('%.2f', ($yh815Num / $yq815Num) * 100)) : 0).'%', //回款率

                'yq15Num' => $yq15Num,
                'yh15Num' => $yh15Num,
                'yq15HkLv' => (($yq15Num != 0) ? (sprintf('%.2f', ($yh15Num / $yq15Num) * 100)) : 0).'%', //回款率
            ];
        }
        $this->assign('tempData', $tempData);

        return view();
    }

    /**
     * 放款统计
     */
    public function loan()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('OpenTime', 'not null')->order('OpenTime ASC')->value('OpenTime');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理时间参数并查询相关所有待数据
                $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

                $where['OpenTime'] = $time;
                $orderData = db('loans_applylist')->where($where)->field(['ID', 'OpenTime', 'ApplyMoney', 'user_type'])->select();

                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $ids = ''; //订单ID集

                    $zfNum = 0; //总放款单数
                    $zfMoney = 0; //总放款金额

                    $xkNum = 0; //新客单数
                    $lkNum = 0; //老客单数

                    $xqNum = '???'; //续期单数
                    foreach ($orderData as $k => $v) {
                        if (strtotime($v['OpenTime']) >= $startTime && strtotime($v['OpenTime']) < $endTime) {
                            ++$zfNum;
                            $zfMoney += $v['ApplyMoney'];
                            $ids = $v['ID'].','.$ids;
                            if ($v['user_type'] == 1) {
                                ++$xkNum;
                            }
                            if ($v['user_type'] == 2) {
                                ++$lkNum;
                            }
                        }
                    }

                    //追加数据
                    $tempData[] = [
                        'time' => $timeArr[$i],     //日期
                        'ids' => rtrim($ids, ','), //订单ID集

                        'zfNum' => $zfNum,
                        'zfMoney' => number_format($zfMoney, 2),

                        'xkNum' => $xkNum,
                        'lkNum' => $lkNum,

                        'xkLv' => (($zfNum != 0) ? (sprintf('%.2f', ($xkNum / $zfNum) * 100)) : 0).'%', //新客放款率
                        'lkLv' => (($zfNum != 0) ? (sprintf('%.2f', ($lkNum / $zfNum) * 100)) : 0).'%', //老客放款率

                        'xqNum' => $xqNum,
                    ];
                }

                //总条数
                $count = count($timeData);

                return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
            }
        }

        return view();
    }

    /**
     * 支出统计
     */
    public function cost()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('OpenTime', 'not null')->order('OpenTime ASC')->value('OpenTime');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            //获取消费数据
            $coWhere['CreateTime'] = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];
            $costData = db('docking_log')->where($coWhere)->select();

            //处理数据
            for ($i = 0; $i < count($timeArr); ++$i) {
                //每日日期区间
                $startTime = strtotime($timeArr[$i]);
                $endTime = $startTime + 86400;

                $sumMoney = 0; //总消费

                $dxNum = 0; //短信条数
                $dxMoney = 0; //短信金额

                $sfNum = 0; //身份认证次数
                $sfMoney = 0; //身份认证金额

                $sjNum = 0; //手机认证次数
                $sjMoney = 0; //手机认证金额

                $fkNum = 0; //风控次数
                $newUser = 0; //新用户次数
                $oldUser = 0; //老用户次数
                $fkMoney = 0; //风控金额

                foreach ($costData as $k => $v) {
                    if (strtotime($v['CreateTime']) >= $startTime && strtotime($v['CreateTime']) < $endTime) {
                        $sumMoney += $v['Price'];
                        if ($v['Type'] == 1) {//短信
                            ++$dxNum;
                            $dxMoney += $v['Price'];
                        }
                        if ($v['Type'] == 2) {//身份认证
                            ++$sfNum;
                            $sfMoney += $v['Price'];
                        }
                        if ($v['Type'] == 3) {//手机认证
                            ++$sjNum;
                            $sjMoney += $v['Price'];
                        }
                        if ($v['Type'] == 4 || $v['Type'] == 5) {
                            ++$fkNum;
                            $fkMoney += $v['Price'];
                            if ($v['IsNew'] == 1) {
                                ++$newUser;
                            }
                            if ($v['IsNew'] == 2) {
                                ++$oldUser;
                            }
                        }
                    }
                }

                $tempData[] = [
                    'time' => $timeArr[$i],     //日期

                    'sumMoney' => number_format($sumMoney, 2),

                    'dxNum' => $dxNum,
                    'dxMoney' => number_format($dxMoney, 2),

                    'sfNum' => $sfNum,
                    'sfMoney' => number_format($sfMoney, 2),

                    'sjNum' => $sjNum,
                    'sjMoney' => number_format($sjMoney, 2),

                    'fkNum' => $fkNum,
                    'newUser' => $newUser,
                    'oldUser' => $oldUser,
                    'fkMoney' => number_format($fkMoney, 2),
                ];
            }

            //总条数
            $count = count($timeData);

            return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
        }

        return view();
    }

    /**
     * 进出账统计
     */
    public function business()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('OpenTime', 'not null')->order('OpenTime ASC')->value('OpenTime');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $tempData[] = [
                        'time' => $timeArr[$i],     //日期
                    ];
                }

                //总条数
                $count = count($timeData);

                return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
            }
        }

        return view();
    }

    /**
     * 财务分析.
     */
    public function Finance()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('OpenTime', 'not null')->order('OpenTime ASC')->value('OpenTime');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理时间参数并查询相关所有待数据
                $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

                //获取时间范围内的放款订单数据
                $fkWhere['OpenTime'] = $time;
                $fkOrderData = db('loans_applylist')->where($fkWhere)->field(['ID', 'OpenTime', 'ApplyMoney', 'AdoptMoney', 'Interest', 'user_type'])->select();

                //获取时间范围内的续借订单数据
                $xqWhere['x.CreateTime'] = $time;
                $xqOrderData = db('loans_xjapplylist')->alias('x')
                    ->join('xb_loans_applylist a', 'x.OrderSn = a.OrderSn', 'LEFT')
                    ->where($xqWhere)
                    ->field(['a.ID' => 'AID', 'x.ID' => 'XID', 'x.TotalMoney', 'x.CreateTime'])
                    ->group('x.ID')
                    ->select();

                //获取时间范围内的已结清的订单数据[全额还款订单]
                $qEhkWhere['a.SjFkTime'] = $time;
                $qEhkWhere['a.LoanStatus'] = 3;
                $qEhkOrderData = db('loans_applylist')->alias('a')
                    ->join('xb_loans_hklist h', 'a.OrderSn = h.OrderSn')
                    ->where($qEhkWhere)
                    ->field('a.ID,SUM(h.TotalMoney) as TotalMoney,a.YyFkTime,a.Interest,a.SjFkTime')
                    ->group('a.ID')
                    ->select();

                //获取时间范围内的部分还款金额
                $bfHkWhere['h.HkTime'] = $time;
                $bfHkWhere['h.Type'] = 2; //类型 部分还款
                $bfHkWhere['a.LoanStatus'] = 2; //状态 2还款中
                $bfHkOrderData = db('loans_hklist')->alias('h')
                    ->join('xb_loans_applylist a', 'h.OrderSn = a.OrderSn')
                    ->where($bfHkWhere)
                    ->field('h.ID,h.HkTime,h.TotalMoney,a.ID as AID')
                    ->group('h.ID')
                    ->select();

                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $fkNum = 0; //放款单数
                    $fkMoney = 0; //放款金额
                    $fkFwMoney = 0; //放款服务费

                    $newFkNum = 0; //新增放款单数
                    $newFkMoney = 0; //新增放款本金
                    $newFwMoney = 0; //新增放款服务费

                    $fjNum = 0; //复借单数
                    $fjMoney = 0; //复借本金
                    $fjFwMoney = 0; //复借服务费

                    $xqNum = 0; //续期单数
                    $xqMoney = 0; //续期金额

                    $qeHkNum = 0; //全额还款单数
                    $qeHkMoney = 0; //全额还款金额
                    $qeHkFwMoney = 0; //全额还款服务费

                    $yqHkNum = 0; //逾期还款单数
                    $yqHkMoney = 0; //逾期还款金额

                    $bfHkMoney = 0; //部分还款金额

                    //计算每日放款订单
                    foreach ($fkOrderData as $k => $v) {
                        if (strtotime($v['OpenTime']) >= $startTime && strtotime($v['OpenTime']) < $endTime) {
                            ++$fkNum;
                            $fkMoney += $v['ApplyMoney'];
                            $fkFwMoney += $v['Interest'];
                            if ($v['user_type'] == 1) {//新用户
                                ++$newFkNum;
                                $newFkMoney += $v['AdoptMoney'];
                                $newFwMoney += $v['Interest'];
                            }
                            if ($v['user_type'] == 2) {//复借订单
                                ++$fjNum;
                                $fjMoney += $v['AdoptMoney'];
                                $fjFwMoney += $v['Interest'];
                            }
                        }
                    }

                    //计算每日续期订单
                    foreach ($xqOrderData as $k => $v) {
                        if (strtotime($v['CreateTime']) >= $startTime && strtotime($v['CreateTime']) < $endTime) {
                            ++$xqNum;
                            $xqMoney += $v['TotalMoney'];
                        }
                    }

                    //计算每日全额还款订单
                    foreach ($qEhkOrderData as $k => $v) {
                        if (strtotime($v['SjFkTime']) >= $startTime && strtotime($v['SjFkTime']) < $endTime) {
                            ++$qeHkNum;
                            $qeHkMoney += $v['TotalMoney'];
                            $qeHkFwMoney += $v['Interest'];
                        }
                        //检测订单是否逾期还款
                        if (strtotime($v['SjFkTime']) > strtotime($v['YyFkTime'])) {
                            $YyFkTime = strtotime($v['YyFkTime']) + 86400; //因为是检测逾期 当天只是到期明天才是逾期 所以加一天的时间戳
                            if ($YyFkTime >= $startTime && $YyFkTime < $endTime) {
                                ++$yqHkNum;
                                $yqHkMoney += $v['TotalMoney'];
                            }
                        }
                    }

                    //计算部分还款
                    foreach ($bfHkOrderData as $k => $v) {
                        if (strtotime($v['HkTime']) >= $startTime && strtotime($v['HkTime']) < $endTime) {
                            $bfHkMoney += $v['TotalMoney'];
                        }
                    }

                    $tempData[] = [
                        'time' => $timeArr[$i],     //日期

                        'fkNum' => $fkNum,
                        'fkMoney' => number_format($fkMoney, 2),
                        'fkFwMoney' => number_format($fkFwMoney, 2),

                        'newFkNum' => $newFkNum,
                        'newFkMoney' => number_format($newFkMoney, 2),
                        'newFwMoney' => number_format($newFwMoney, 2),

                        'fjNum' => $fjNum,
                        'fjMoney' => number_format($fjMoney, 2),
                        'fjFwMoney' => number_format($fjFwMoney, 2),

                        'xqNum' => $xqNum,
                        'xqMoney' => number_format($xqMoney, 2),

                        'qeHkNum' => $qeHkNum,
                        'qeHkMoney' => number_format($qeHkMoney, 2),
                        'qeHkFwMoney' => number_format($qeHkFwMoney, 2),

                        'yqHkNum' => $yqHkNum,
                        'yqHkMoney' => number_format($yqHkMoney, 2),

                        'bfHkMoney' => number_format($bfHkMoney, 2),
                    ];
                }

                //总条数
                $count = count($timeData);

                return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
            }
        }

        return view();
    }

    /**
     * 催收分析.
     */
    public function collection()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,time');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['time'])) {
                $strTime = db('loans_applylist')->where('cuishourenTime', 'not null')->order('OpenTime ASC')->value('cuishourenTime');
                $endTime = date('Y-m-d', time());
                $postData['time'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理时间参数并查询相关所有待数据
                $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];
                $where['cuishourenTime'] = $time;
                $orderData = db('loans_applylist')->alias('a')
                    ->join('xb_sys_administrator s', 'a.cuishourenID = s.ID', 'LEFT')
                    ->join('xb_loans_hklist h', 'a.OrderSn = h.OrderSn', 'LEFT')
                    ->where($where)
                    ->group('a.ID')
                    ->field('a.cuishourenTime,a.ID,a.ApplyMoney,a.LoanStatus,SUM(h.TotalMoney) as TotalMoney')
                    ->select();

                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $ids = ''; //订单ID

                    $fpRsNum = 0; //分配人数
                    $fpMoney = 0; //分配金额
                    $hkNum = 0; //还款单数
                    $hkMoney = 0; //还款金额

                    foreach ($orderData as $k => $v) {
                        if (strtotime($v['cuishourenTime']) >= $startTime && strtotime($v['cuishourenTime']) < $endTime) {
                            ++$fpRsNum;
                            $fpMoney += $v['ApplyMoney'];
                            $ids = $v['ID'].','.$ids;
                            if ($v['LoanStatus'] == 3) {
                                ++$hkNum;
                                $hkMoney += $v['TotalMoney'];
                            }
                        }
                    }

                    $tempData[] = [
                        'time' => $timeArr[$i],
                        'ids' => rtrim($ids, ','), //订单ID集

                        'fpRsNum' => $fpRsNum,
                        'fpMoney' => number_format($fpMoney, 2),

                        'hkNum' => $hkNum,
                        'hkMoney' => number_format($hkMoney, 2),
                        'hkLv' => (($fpRsNum != 0) ? (sprintf('%.2f', ($hkNum / $fpRsNum) * 100)) : 0).'%', //还款率
                    ];
                }

                //总条数
                $count = count($timeData);

                return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
            }
        }

        return view();
    }

    /**
     * 还款统计 - 单数.
     */
    public function repayment()
    {
        if (request()->isAjax()) {
            $postData = Request()->only('page,limit,ApplyTime');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;

            //检测是否有时间参数没有这抓取数据库预约还款时间最早一个与最晚一个用于计算总页数
            if (!isset($postData['ApplyTime'])) {
                $strTime = db('loans_applylist')->where('ApplyTime', 'not null')->order('ApplyTime ASC')->value('ApplyTime');
                $endTime = date('Y-m-d', time());
                $postData['ApplyTime'] = $strTime.' - '.$endTime;
            }

            $timeData = $this->getTimeData($page, $limit, isset($postData['ApplyTime']) ? $postData['ApplyTime'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);

            if ($timeArr) {
                //处理时间参数并查询相关所有待数据
                $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

                //获取主订单信息与关联的还款数据
                $orWhere['a.YyFkTime2'] = $time;
                $orWhere['a.LoanStatus'] = ['in', '2,3'];
                $orderData = db('loans_applylist')->alias('a')
                    ->join('xb_loans_hklist h', 'a.ID = h.ApplyID', 'LEFT')
                    ->join('xb_loans_xjapplylist x','a.ID = x.AppID','LEFT')
                    ->group('a.ID')
                    ->where($orWhere)
                    ->field('a.YyFkTime2,a.ApplyMoney,a.daoqiMoney,a.LoanStatus,a.app_type,SUM(h.TotalMoney) as hTotalMoney,h.Type as hType,x.ID as xID')
                    ->select();

                //获取续期订单与关联的订单数据并获取还款数据
                $xqWhere['x.YyFkTime'] = $time;
                $xqWhere['a.LoanStatus'] = ['in', '2,3'];
                $xqOrderData = db('loans_xjapplylist')->alias('x')
                    ->join('xb_loans_applylist a', 'x.AppID = a.ID', 'LEFT')
                    ->join('xb_loans_hklist h', 'a.ID = h.ApplyID', 'LEFT')
                    ->where($xqWhere)
                    ->group('x.ID')
                    ->field('x.CreateTime,x.YyFkTime,a.ApplyMoney,a.daoqiMoney,a.LoanStatus,a.app_type,SUM(h.TotalMoney) as hTotalMoney,h.Type as hType')
                    ->select();

                //处理数据
                for ($i = 0; $i < count($timeArr); ++$i) {
                    //每日日期区间
                    $startTime = strtotime($timeArr[$i]);
                    $endTime = $startTime + 86400;

                    $yhNum = 0; //应还单数
                    $shNum = 0; //已还单数
                    $qeNum = 0; //全额单数
                    $xqNum = 0; //续期单数
                    $fjNum = 0; //复借单数

                    $yhMoney = 0; //应还金额
                    $shMoney = 0; //已还金额
                    $qeMoney = 0; //全额金额
                    $xqMoney = 0; //续期金额
                    $fjMoney = 0; //复借金额

                    $sjYhNum = 0; //首借应还单数
                    $sjShNum = 0; //首借已还单数
                    $sjQeNum = 0; //首借全额单数
                    $sjXqNum = 0; //首借续期单数

                    $sjYhMoney = 0; //首借应还金额
                    $sjShMoney = 0; //首借已还金额
                    $sjQeMoney = 0; //首借全额金额
                    $sjXqMoney = 0; //首借续期金额

                    $xjYhNum = 0; //续期应还单数
                    $xjShNum = 0; //续期已还单数
                    $xjQeNum = 0; //续期全额单数
                    $xjXqNum = 0; //续期单数

                    $xjYhMoney = 0; //续期应还金额
                    $xjShMoney = 0; //续期已还金额
                    $xjQeMoney = 0; //续期全额金额
                    $xjXqMoney = 0; //续期金额

                    $fjYhNum = 0; //复借应还单数
                    $fjShNum = 0; //复借已还单数
                    $fjQeNum = 0; //复借全额单数
                    $fjXqNum = 0; //复借续期单数

                    $fjYhMoney = 0; //复借应还金额
                    $fjShMoney = 0; //复借已还金额
                    $fjQeMoney = 0; //复借全额金额
                    $fjXqMoney = 0; //复借续期金额

                    foreach ($orderData as $k => $v) {
                        if (strtotime($v['YyFkTime2']) >= $startTime && strtotime($v['YyFkTime2']) < $endTime) {
                            ++$yhNum;
                            $yhMoney += $v['daoqiMoney'];
                            if ($v['LoanStatus'] == 3) {//3已结清订单
                                ++$shNum;
                                $shMoney += $v['hTotalMoney'];
                                
                                if ($v['hType'] == 4 || $v['hType'] == 6) {//4线上全额 6线下全额
                                    ++$qeNum;
                                    $qeMoney += $v['hTotalMoney'];
                                }
                            }

                            //首借
                            if ($v['app_type'] == 1) {
                                ++$sjYhNum;
                                $sjYhMoney += $v['daoqiMoney'];
                                if ($v['LoanStatus'] == 3) {//首借已还
                                    ++$sjShNum;
                                    $sjShMoney += $v['hTotalMoney'];

                                    if ($v['hType'] == 4 || $v['hType'] == 6) {//4线上全额 6线下全额
                                        ++$sjQeNum;
                                        $sjQeMoney += $v['hTotalMoney'];
                                    }
                                }
                            }

                            //复借
                            if ($v['app_type'] == 2) {
                                ++$fjNum;
                                $fjMoney += $v['ApplyMoney'];

                                ++$fjYhNum;
                                $fjYhMoney += $v['daoqiMoney'];
                                if ($v['LoanStatus'] == 3) {//复借已还
                                    ++$fjShNum;
                                    $fjShMoney += $v['hTotalMoney'];

                                    if ($v['hType'] == 4 || $v['hType'] == 6) {//4线上全额 6线下全额
                                        ++$fjQeNum;
                                        $fjQeMoney += $v['hTotalMoney'];
                                    }
                                }
                            }
                        }
                    }

                    foreach ($xqOrderData as $k => $v) {
                        if (strtotime($v['YyFkTime']) >= $startTime && strtotime($v['YyFkTime']) < $endTime) {
                            ++$yhNum;
                            $yhMoney += $v['daoqiMoney'];

                            //续期
                            ++$xqNum;
                            $xqMoney += $v['ApplyMoney'];

                            if ($v['LoanStatus'] == 3) {//3已结清订单
                                ++$shNum;
                                $shMoney += $v['hTotalMoney'];

                                if ($v['hType'] == 4 || $v['hType'] == 6) {//4线上全额 6线下全额
                                    ++$qeNum;
                                    $qeMoney += $v['hTotalMoney'];
                                }
                            }

                            //续期
                            ++$xjYhNum;
                            $xjYhMoney += $v['ApplyMoney'];
                            if ($v['LoanStatus'] == 3) {//3已结清订单
                                ++$xjShNum;
                                $xjShMoney += $v['hTotalMoney'];

                                if ($v['hType'] == 4 || $v['hType'] == 6) {//4线上全额 6线下全额
                                    ++$xjQeNum;
                                    $xjQeMoney += $v['hTotalMoney'];
                                }
                            }
                        }
                    }

                    $tempData[] = [
                        'time' => $timeArr[$i],

                        //单数
                        'yhNum' => $yhNum,
                        'shNum' => $shNum,
                        'whNum' => $yhNum - $shNum, //未还单数 = 应还单数-已还单数
                        'sumHkLv' => (($yhNum != 0) ? (sprintf('%.2f', ($shNum / $yhNum) * 100)) : 0).'%', //还款率 = (已还单数/应还单数)*100%
                        'qeNum' => $qeNum,
                        'sumQeLv' => (($yhNum != 0) ? (sprintf('%.2f', ($qeNum / $yhNum) * 100)) : 0).'%', //全额率 = (全额单数/应还单数)*100%
                        'xqNum' => $xqNum,
                        'sumXqLv' => (($shNum != 0) ? (sprintf('%.2f', ($xqNum / $shNum) * 100)) : 0).'%', //续期率 = (续期单数/已还单数)*100%
                        'fjNum' => $fjNum,
                        'fjLv' => (($shNum != 0) ? (sprintf('%.2f', ($fjNum / $shNum) * 100)) : 0).'%', //复借率 = (复借单数/应还单数)*100%

                        'sjYhNum' => $sjYhNum,
                        'sjShNum' => $sjShNum,
                        'sjWhNum' => $sjYhNum - $sjShNum, //首借未还单数 = 首借应还单数-首借已还单数
                        'sjHkLv' => (($sjYhNum != 0) ? (sprintf('%.2f', ($sjShNum / $sjYhNum) * 100)) : 0).'%', //首借单数还款率 = (首借已还单数/首借应还单数)*100%
                        'sjQeNum' => $sjQeNum,
                        'sjXqNum' => $sjXqNum,

                        'xjYhNum' => $xjYhNum,
                        'xjShNum' => $xjShNum,
                        'xjWhNum' => $xjYhNum - $xjShNum, //续借未还单数 = 续借应还单数-续借已还单数
                        'xjHkLv' => (($xjYhNum != 0) ? (sprintf('%.2f', ($xjShNum / $xjYhNum) * 100)) : 0).'%', //续借单数还款率 = (续借已还单数/续借应还单数)*100%
                        'xjQeNum' => $xjQeNum,
                        'xjXqNum' => $xjXqNum,

                        'fjYhNum' => $fjYhNum,
                        'fjShNum' => $fjShNum,
                        'fjWhNum' => $fjYhNum - $fjShNum, //续借未还单数 = 续借应还单数-续借已还单数
                        'fjHkLv' => (($fjYhNum != 0) ? (sprintf('%.2f', ($fjShNum / $fjYhNum) * 100)) : 0).'%', //续借单数还款率 = (续借已还单数/续借应还单数)*100%
                        'fjQeNum' => $fjQeNum,
                        'fjXqNum' => $fjXqNum,

                        //金额
                        'yhMoney' => number_format($yhMoney, 2),
                        'shMoney' => number_format($shMoney, 2),
                        'whMoney' => number_format(($yhMoney - $shMoney), 2), //未还金额 = 应还金额-已还金额
                        'sumHkLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($shMoney / $yhMoney) * 100)) : 0).'%', //金额还款率 = (已还金额/应还金额)*100%
                        'qeMoney' => number_format($qeMoney, 2),
                        'sumQeLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($qeMoney / $yhMoney) * 100)) : 0).'%', //全额率 = (全额金额/应还金额)*100%
                        'xqMoney' => number_format($xqMoney,2),
                        'sumXqLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($xqMoney / $yhMoney) * 100)) : 0).'%', //续期率 = (续期金额/应还金额)*100%

                        'fjMoney' => number_format($fjMoney,2),
                        'fjLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($fjMoney / $yhMoney) * 100)) : 0).'%',

                        'sjYhMoney' => number_format($sjYhMoney,2),
                        'sjShMoney' => number_format($sjShMoney,2),
                        'sjWhMoney' => number_format(($sjYhMoney - $sjShMoney),2),
                        'sjHkLv' => (($sjYhMoney != 0) ? (sprintf('%.2f', ($sjShMoney / $sjYhMoney) * 100)) : 0).'%',
                        'sjQeMoney' => number_format($sjQeMoney,2),
                        'sjXqMoney' => number_format($sjXqMoney,2),

                        'xjYhMoney' => number_format($xjYhMoney,2),
                        'xjShMoney' => number_format($xjShMoney,2),
                        'xjWhMoney' => number_format(($xjYhMoney - $xjShMoney),2),
                        'xjHkLv' => (($xjYhMoney != 0) ? (sprintf('%.2f', ($xjShMoney / $xjYhMoney) * 100)) : 0).'%',
                        'xjQeMoney' => number_format($xjQeMoney,2),
                        'xjXqMoney' => number_format($xjXqMoney,2),
                        
                        'fjYhMoney' => number_format($fjYhMoney,2),
                        'fjShMoney' => number_format($fjShMoney,2),
                        'fjWhMoney' => number_format(($fjYhMoney - $fjShMoney),2),
                        'fjHkLv' => (($fjYhMoney != 0) ? (sprintf('%.2f', ($fjShMoney / $fjYhMoney) * 100)) : 0).'%',
                        'fjQeMoney' => number_format($fjQeMoney,2),
                        'fjXqMoney' => number_format($fjXqMoney,2),
                    ];
                }

                //总条数
                $timeData = [];
                $count = count($timeData);

                return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
            }
        }
    }

    /**
     * 还款统计 - 查看订单渠道.
     */
    public function repaymentChannel()
    {
        if (request()->isAjax()) {
            //获取应还订单数据
            //处理时间参数并查询相关所有待数据
            $time = ['between', input('time').','.input('time').' 23:59:59'];

            //获取应还订单数据
            $yhWhere['a.YyFkTime2'] = $time;
            $yhWhere['LoanStatus'] = ['in', '2,3'];
            $yhOrderData = db('loans_applylist')->alias('a')
                ->join('xb_loans_hklist h', 'a.ID = h.ApplyID', 'LEFT')
                ->join('xb_loans_xjapplylist x', 'a.ID = x.AppID', 'LEFT')
                ->join('xb_mem_info m', 'a.UserID = m.ID', 'LEFT')
                ->join('xb_tg_admin t', 'm.TgadminID = t.ID', 'LEFT')
                ->where($yhWhere)
                ->group('a.ID')
                ->field('a.ID,a.YyFkTime2,a.ApplyMoney,a.daoqiMoney,a.LoanStatus,a.user_type,a.is_fujie,SUM(h.TotalMoney) as hTotalMoney,h.pay as hpay,a.user_type,t.Name,x.YyFkTime as xYyFkTime,x.ID as XID')
                ->select();

            $channel = [];
            foreach (array_column($yhOrderData, 'Name') as $K => $v) {
                if (!in_array($v, $channel)) {
                    array_push($channel, $v);
                }
            }

            //处理数据，如果订单续期将自己也追加到源数据中，并把预约时间更新为续期的时间
            foreach ($yhOrderData as $k => $v) {
                if ($v['XID']) {
                    $v['YyFkTime2'] = $v['xYyFkTime'];
                    array_push($yhOrderData, $v);
                }
            }

            $tempData = [];
            for ($i = 0; $i < count($channel); ++$i) {
                $yhNum = 0; //应还单数
                $shNum = 0; //已还单数
                $qeNum = 0; //全额单数
                $zqNum = 0; //展期单数

                $yhMoney = 0; //应还金额
                $shMoney = 0; //已还金额
                $qeMoney = 0; //全额金额
                $zqMoney = 0; //展期金额

                $xkYhNum = 0; //新客应还单数
                $xkYhMoney = 0; //新客应还金额
                $xkShNum = 0; //新客已还单数
                $xkShMoney = 0; //新客已还金额

                $lkYhNum = 0; //老客应还单数
                $lkYhMoney = 0; //老客应还金额
                $lkShNum = 0; //老客已换单数
                $lkShMoney = 0; //老客已还金额

                foreach ($yhOrderData as $k => $v) {
                    if ($channel[$i] == $v['Name']) {
                        ++$yhNum;
                        $yhMoney += $v['daoqiMoney'];
                        if ($v['LoanStatus'] == 3) {//3已结清订单
                            ++$shNum;
                            $shMoney += $v['hTotalMoney'];
                        }
                        if ($v['hpay'] == 4 || $v['hpay'] == 6) {//4线上全额 6线下全额
                            ++$qeNum;
                            $qeMoney += $v['hTotalMoney'];
                        }
                        if ($v['is_fujie'] == 1) {//1是复借
                            ++$zqNum;
                            $zqMoney += $v['ApplyMoney'];
                        }
                        if ($v['user_type'] == 1) {//新客
                            ++$xkYhNum;
                            $xkYhMoney += $v['daoqiMoney'];
                            if ($v['LoanStatus'] == 3) {
                                ++$xkShNum;
                                $xkShMoney += $v['hTotalMoney'];
                            }
                        }
                        if ($v['user_type'] == 2) {
                            ++$lkYhNum;
                            $lkYhMoney += $v['daoqiMoney'];
                            if ($v['LoanStatus'] == 3) {
                                ++$lkShNum;
                                $lkShMoney += $v['hTotalMoney'];
                            }
                        }
                    }
                }

                $tempData[] = [
                    'name' => $channel[$i],

                    //单数
                    'yhNum' => $yhNum,
                    'shNum' => $shNum,
                    'whNum' => $yhNum - $shNum, //未还单数 = 应还单数-已还单数
                    'numHkLv' => (($yhNum != 0) ? (sprintf('%.2f', ($shNum / $yhNum) * 100)) : 0).'%', //还款率 = (已还单数/应还单数)*100%

                    'qeNum' => $qeNum,
                    'zqNum' => $zqNum,

                    'numQeLv' => (($yhNum != 0) ? (sprintf('%.2f', ($qeNum / $yhNum) * 100)) : 0).'%', //单数全额率 = (全额单数/应还单数)*100%
                    'numZqLv' => (($yhNum != 0) ? (sprintf('%.2f', ($zqNum / $yhNum) * 100)) : 0).'%', //单数展期率 = (展期单数/应还单数)*100%

                    'xkYhNum' => $xkYhNum,
                    'xkShNum' => $xkShNum,
                    'xkWhNum' => $xkYhNum - $xkShNum, //新客未还单数 = 新客应还单数-新客已还单数
                    'numXkHkLv' => (($xkYhNum != 0) ? (sprintf('%.2f', ($xkShNum / $xkYhNum) * 100)) : 0).'%', //新客单数还款率 = (新客已还单数/新客应还单数)*100%

                    'lkYhNum' => $lkYhNum,
                    'lkShNum' => $lkShNum,
                    'lkWhNum' => $lkYhNum - $lkShNum, //老客未还单数 = 老客应还单数-老客已还单数
                    'numLkHkLv' => (($lkYhNum != 0) ? (sprintf('%.2f', ($lkShNum / $lkYhNum) * 100)) : 0).'%', //老客单数还款率 = (老客已还单数/老客应还单数)*100%

                    //金额
                    'yhMoney' => number_format($yhMoney, 2),
                    'shMoney' => number_format($shMoney, 2),
                    'whMoney' => number_format(($yhMoney - $shMoney), 2), //未还金额 = 应还金额-已还金额
                    'moneyHkLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($shMoney / $yhMoney) * 100)) : 0).'%', //金额还款率 = (已还金额/应还金额)*100%

                    'qeMoney' => number_format($qeMoney, 2),
                    'zqMoney' => number_format($zqMoney, 2),

                    'moneyQeLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($qeMoney / $yhMoney) * 100)) : 0).'%', //金额全额率 = (全额金额/应还金额)*100%
                    'moneyZqLv' => (($yhMoney != 0) ? (sprintf('%.2f', ($zqMoney / $yhMoney) * 100)) : 0).'%', //金额展期率 = (展期金额/应还金额)*100%

                    'xkYhMoney' => number_format($xkYhMoney, 2),
                    'xkShMoney' => number_format($xkShMoney, 2),
                    'xkWhMoney' => number_format(($xkYhMoney - $xkShMoney), 2), //新客未还金额 = 新客应还金额-新客已还金额
                    'moneyXkHkLv' => (($xkYhMoney != 0) ? (sprintf('%.2f', ($xkShMoney / $xkYhMoney) * 100)) : 0).'%', //新客金额还款率 = (新客已还金额/新客应还金额)*100%

                    'lkYhMoney' => number_format($lkYhMoney, 2),
                    'lkShMoney' => number_format($lkShMoney, 2),
                    'lkWhMoney' => number_format(($lkYhMoney - $lkShMoney), 2), //老客未还金额 = 老客应还金额-老客已还金额
                    'moneyLkHkLv' => (($lkYhMoney != 0) ? (sprintf('%.2f', ($lkShMoney / $lkYhMoney) * 100)) : 0).'%', //老客金额还款率 = (老客已还金额/老客应还金额)*100%
                ];
            }
            //总条数
            $count = count($channel);

            return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
        }

        $this->assign('time', input('time'));

        return view(input('viewType'));
    }

    /**
     * 催收分析 - 查看催收员.
     */
    public function collectionList()
    {
        $where['a.ID'] = ['in', input('ids')];
        $collectionData = db('loans_applylist')->alias('a')
            ->join('xb_sys_administrator s', 'a.cuishourenID = s.ID', 'LEFT')
            ->join('xb_loans_hklist h', 'a.OrderSn = h.OrderSn', 'LEFT')
            ->where($where)
            ->group('a.ID')
            ->field('a.cuishourenTime,a.ID,a.ApplyMoney,a.LoanStatus,SUM(h.TotalMoney) as TotalMoney,s.UserName')
            ->select();

        $collection = [];
        foreach (array_column($collectionData, 'UserName') as $K => $v) {
            if (!in_array($v, $collection)) {
                array_push($collection, $v);
            }
        }

        for ($i = 0; $i < count($collection); ++$i) {
            $fpNum = 0; //分配人数(也就是该人员的分配订单数)
            $fpMoney = 0; //分配金额

            $hkNum = 0; //还款单数
            $hkMoney = 0; //还款金额

            foreach ($collectionData as $k => $v) {
                if ($collection[$i] == $v['UserName']) {
                    ++$fpNum;
                    $fpMoney += $v['ApplyMoney'];

                    if ($v['LoanStatus'] == 3) {
                        ++$hkNum;
                        $hkMoney += $v['TotalMoney'];
                    }
                }
            }

            //追加数据
            $tempData[] = [
                'csName' => $collection[$i],
                'fpNum' => $fpNum,
                'fpMoney' => $fpMoney,

                'hkNum' => $hkNum,
                'hkMoney' => $hkMoney,
                'hkLv' => (($fpNum != 0) ? (sprintf('%.2f', ($hkNum / $fpNum) * 100)) : 0).'%', //还款率
            ];
        }
        $this->assign('tempData', $tempData);

        return view();
    }

    /**
     * 根据ID获取订单信息.
     *
     * @param string $ids 订单ID集
     *
     * @return array
     */
    public function getOrderInfo()
    {
        //订单状态  1等待放款 2已放款 3已完成 4已取消 5已拒绝 6等待银行打款 7待人工审核
        $loanStatus = [0 => '未知', 1 => '等待放款', 2 => '已放款', 3 => '已完成', 4 => '已取消', 5 => '已拒绝', 6 => '等待银行打款', 7 => '等待人工审核'];
        //审核状态 1人工审核成功  5人工审核失败 2机审成功 4机审失败
        $status = [0 => '未知', 1 => '人工审核成功', 2 => '机审成功', 4 => '机审失败', 5 => '人工审核失败'];
        //放款方式 支付方式（放款方式） 1微信 2支付宝 3银行卡(后台手动放款)4银行卡(自动放款)
        $payType = [1 => '微信', 2 => '支付宝', 3 => '银行卡(后台手动放款)', 4 => '银行卡(自动放款)'];

        $fields = 'a.ID,a.OrderSn,a.ApplyTime,a.ApplyMoney,a.AdoptMoney,a.ShTime,a.Status,a.OpenTime,a.YyFkTime,a.LoanStatus,a.pay,m.ID as MID,m.TrueName,m.Mobile,x.ID as XID,count(x.ID) as xNum,h.ID as HIDS,count(h.ID) as hNum,b.BankName,b.BankNo';
        $orderData = db('loans_applylist')->alias('a')
            ->join('xb_mem_info m', 'a.UserID = m.ID', 'LEFT')
            ->join('xb_renzen_bank b', 'm.ID = b.UserID', 'LEFT')
            ->join('xb_loans_xjapplylist x', 'a.OrderSn = x.OrderSn', 'LEFT')
            ->join('xb_loans_hklist h', 'a.OrderSn = h.OrderSn', 'LEFT')
            ->where(['a.ID' => ['in', input('ids')]])
            ->group('a.ID')
            ->field($fields)
            ->select();
//        $orderData = db('loans_applylist')->where(['ID' => ['in',input('ids')]])->field(['ID','OrderSn','ApplyTime','ShTime','Status','OpenTime','YyFkTime','LoanStatus'])->select();

        foreach ($orderData as $k => $v) {
            $orderData[$k]['LoanStatus'] = $loanStatus[$v['LoanStatus']];
            $orderData[$k]['Status'] = $status[$v['Status']];
            $orderData[$k]['pay'] = $payType[$v['pay']];
        }
        $this->assign('orderData', $orderData);

        return view(input('viewType'));
    }

    /**
     * 推广统计
     */
    public function extension()
    {
        //获取用户禁止查看的的字段值，更具字段值获取对应组合前段所需的cols数据格式
        $field = db('sys_administrator')->where(['ID' => session('id')])->value('TemplateField');

        if (request()->isAjax()) {
            //获取请求参数
            $postData = Request()->only('page,limit,time,adminID');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;
            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);
            //获取查询时间范围
            $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

            //根据角色获取对应渠道信息
            $roleID = session('info.RoleID');
            if ($roleID == 48) {
                $tdData = db('tg_admin')->where(['AdminID' => session('id')])->column('ID');
                if ($tdData) {
                    $visitWhere['TgAdminID'] = ['in', $tdData];
                    $usWhere['i.TgadminID'] = ['in', $tdData];
                }else{
                    $visitWhere['TgAdminID'] = 'empty';
                    $usWhere['i.TgadminID'] = 'empty';
                }
            }

            if (isset($postData['adminID']) && !empty($postData['adminID'])) {
                $visitWhere['TgAdminID'] = $postData['adminID'];
                $usWhere['i.TgadminID'] = $postData['adminID'];
            }

            //获取范围内的到访用户信息
            $visitWhere['CreateTime'] = $time;
            $visitData = db('tg_record')->where($visitWhere)->field('ID,CreateTime,Type')->select();

            $usWhere['i.RegTime'] = $time;
            //获取范围内的注册用户与订单信息
            $userJoinOrder = db('mem_info')->alias('i')
                ->join('xb_loans_applylist a', 'i.ID = a.UserID', 'LEFT')
                ->join('xb_tg_admin t', 'i.TgadminID = t.ID', 'LEFT')
                ->where($usWhere)
                ->field('RegTime,a.ID,a.LoanStatus,t.Kouliang,t.TuiGuangFangShi,t.DanJia,a.jishen,a.OrderSn')
                ->group('i.ID')
                ->select();

            $tempData = [];
            for ($i = 0; $i < count($timeArr); ++$i) {
                //每日日期区间
                $startTime = strtotime($timeArr[$i]);
                $endTime = $startTime + 86400;

                $pvNum = 0; //pv访问数
                $uaNum = 0; //ua点击注册数
                $aa = 0;
                foreach ($visitData as $k => $v) {
                    if (strtotime($v['CreateTime']) >= $startTime && strtotime($v['CreateTime']) < $endTime) {
                        if ($v['Type'] == 1) {
                            ++$pvNum;
                        }
                        if ($v['Type'] == 2) {
                            ++$uaNum;
                        }
                        ++$aa;
                    }
                }

                $zcNum = 0; //注册数
                $sqNum = 0; //申请数
                $fkNum = 0; //放款数
                $klLv = 0; //扣量比例%
                $tgMoney = 0; //推广金额
                $sq0FenNum = 0; //0分申请数
                foreach ($userJoinOrder as $k => $v) {
                    if (strtotime($v['RegTime']) >= $startTime && strtotime($v['RegTime']) < $endTime) {
                        ++$zcNum;
                        if ($v['ID']) {
                            ++$sqNum;
                        }
                        if ($v['ID'] && in_array($v['LoanStatus'], [2, 3])) {
                            ++$fkNum;
                        }
                        $klLv = $v['Kouliang'];

                        if ($v['TuiGuangFangShi'] == 'CPS') {
                            $tgMoney = $v['DanJia'] * $fkNum;
                        }
                        if ($v['TuiGuangFangShi'] == 'CPA') {
                            $tgMoney = $v['DanJia'] * $zcNum;
                        }
                        if ($v['TuiGuangFangShi'] == 'UV') {
                            $tgMoney = $v['DanJia'] * $uaNum;
                        }
                        //如果有订单并且机审分为0
                        if($v['OrderSn'] && $v['jishen'] == 0){
                            ++$sq0FenNum;
                        }
                    }
                }

                //检测0分率是否超过15% 超过给字体标红 低于15%标绿
                $sq0FenLv = (($sqNum != 0) ? (sprintf('%.2f', ($sq0FenNum / $sqNum) * 100)) : 0);
                if($sq0FenLv > 15){
                    $sq0FenLv = '<span style="color:red;">'.$sq0FenLv.'%</span>';
                }else{
                    $sq0FenLv = '<span style="color:#00B050;">'.$sq0FenLv.'%</span>';
                }

                //检测申请率超过70% 超过给字体标红 低于40%标绿
                $sqLv = (($zcNum != 0) ? (sprintf('%.2f', ($sqNum / $zcNum) * 100)) : 0);
                if($sqLv > 75){
                    $sqLv = '<span style="color:red;">'.$sqLv.'%</span>';
                }elseif($sqLv < 40){
                    $sqLv = '<span style="color:#00B050;">'.$sqLv.'%</span>';
                }else{
                    $sqLv = $sqLv.'%';
                }

                $tempData[] = [
                    'time' => $timeArr[$i],

                    'pvNum' => $pvNum,
                    'uaNum' => $uaNum,

                    'zcNum' => $zcNum,
                    'klNum' => floor($zcNum - ($zcNum * ($klLv / 100))),

                    'sqNum' => $sqNum,
                    'fkNum' => $fkNum,

                    'sqLv' => $sqLv, //申请率

                    'sq0FenNum' => $sq0FenNum, //0分申请数（订单风控分）
                    'sq0FenLv' => $sq0FenLv, //0分率（订单风控分）

                    'fkLv' => (($zcNum != 0) ? (sprintf('%.2f', ($fkNum / $zcNum) * 100)) : 0).'%', //放款率

                    'tgMoney' => $tgMoney,
                    'zcUvLv' => (($pvNum != 0) ? (sprintf('%.2f', ($uaNum / $pvNum) * 100)) : 0).'%', //注册到uv率
                ];

                //检测是否贷超用户获取对应显示数据
                if (isset($field) && !empty($field)) {
                    $fields = explode(',', $field);
                    foreach ($tempData[$i] as $kk => $vv) {
                        if (!in_array($kk, $fields)) {
                            unset($tempData[$i][$kk]);
                        }
                    }
                }
            }

            $count = count($timeData);

            return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
        }

        //获取登陆角色ID 如果是贷超角色仅获对应可查看的渠道信息
        (session('info.RoleID') == 48) ? $where['AdminID'] = session('id') : $where = [];
        $data = db('tg_admin')->where($where)->field('ID,Name')->select();
        $this->assign('data', $data);

        //检测用户是否有禁止查看的字段，有便从初始模板中删除，没有则可查看所有
        if (isset($field) && !empty($field)) {
            $fields = explode(',', $field);
            $tempStr = $this->setViewField($fields ?? '');
        } else {
            $tempStr = $this->setViewField('');
        }

        $this->assign('tempStr', $tempStr);

        return view();
    }

    /**
     * 定义cols前端渲染模板
     *
     * @param string $templateField 可查看的字段名称
     */
    public function setViewField($templateField)
    {
        $tempStr = '';

        //初始模板 
        $temp = [
            'time' => '{field: \'time\', title: "<p style=\'text-align:center;\'>日期</p>", width: 110,rowspan: 2,fixed: \'left\'}',
            'pvNum' => '{field: \'pvNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日访问推广页的用户数 IP去重\'>pv用户访问数?</p>"}',
            'uaNum' => '{field: \'uaNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日推广页点击注册的人数 IP去重\'>ua点击注册数?</p>"}',
            'zcNum' => '{field: \'zcNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日注册的用户数\'>注册数量?</p>"}',
            'klNum' => '{field: \'klNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'扣量后的数量 = 当日注册的用户数/渠道扣量比列\'>扣量后的数量?</p>"}',
            'sqNum' => '{field: \'sqNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日注册人数中申请借款的人数 用户A在1号注册，2号申请，申请数计算在1号\'>申请人数?</p>"}',
            'sq0FenNum' => '{field: \'sq0FenNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日注册用户申请订单的魔蝎0分数，用户A在1号注册，2号申请，计算在1号\'>0分申请数?</p>"}',
            'sq0FenLv' => '{field: \'sq0FenLv\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'(当日0分申请数/申请人数)*100%\'>0分率?</p>"}',
            'fkNum' => '{field: \'fkNum\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'当日注册人数中的放款人数 用户A在1号放款，2号放款，放款数计算在1号\'>放款人数?</p>"}',
            'sqLv' => '{field: \'sqLv\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'申请率 = (申请人数/注册人数)*100%\'>申请率?</p>"}',
            'fkLv' => '{field: \'fkLv\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'放款率 = (放款人数/注册人数)*100%\'>放款率?</p>"}',
            'tgMoney' => '{field: \'tgMoney\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'推广金额 = 推广方式为CPS【放款人数*单价】 推广方式为CPA【注册人数*单价】 推广方式为UV【ua点击数*单价】 \'>推广金额?</p>"}',
            'zcUvLv' => '{field: \'zcUvLv\', width: 120, title: "<p style=\'text-align:center\' lay-tips=\'注册到uv率 = (注册人数/ua点击数)*100%\'>注册到ua率?</p>"}',
        ];

        //检测贷超角色禁止查看的字段是否在初始模板中，在既删除，将其余字段拼接并返回
        if ($templateField) {
            foreach ($temp as $k => $v) {
                if (!in_array($k, $templateField)) {
                    unset($temp[$k]);
                }
            }
        }

        foreach ($temp as $k => $v) {
            $tempStr = $tempStr.','.$v;
        }

        return ltrim($tempStr, ',');
    }

    /**
     * 渠道统计
     */
    public function channelSum()
    {
        if (request()->isAjax()) {
            //获取请求参数
            $postData = Request()->only('page,limit,time,adminID');
            $page = $postData['page'] ?? 1;
            $limit = $postData['limit'] ?? 10;
            $timeData = $this->getTimeData($page, $limit, isset($postData['time']) ? $postData['time'] : '');

            //获取当前请求显示页的时间参数
            $timeArr = array_slice($timeData, ($page - 1) * $limit, $limit);
            //获取查询时间范围
            $time = ['between', end($timeArr).','.reset($timeArr).' 23:59:59'];

            if (isset($postData['adminID']) && !empty($postData['adminID'])) {
                $where['m.TgadminID'] = $postData['adminID'];
            }
            $where['m.RegTime'] = $time;
            $data = db('mem_info')->alias('m')
                ->join('xb_loans_applylist a', 'm.ID = a.UserID', 'LEFT')
                ->where($where)
                ->group('m.ID')
                ->field('m.ID,m.isID,m.isMobile,m.isSocial,m.isBank,m.RegTime,m.TgadminID,a.ID as AID,a.LoanStatus,a.ApplyTime,a.OrderSn,a.jishen')
                ->select();

            $tempData = [];
            for ($i = 0; $i < count($timeArr); ++$i) {
                //每日日期区间
                $startTime = strtotime($timeArr[$i]);
                $endTime = $startTime + 86400;

                $zcNum = 0; //注册人数
                $sfNum = 0; //身份认证数
                $sjNum = 0; //手机认证数
                $sjNums = 0; //社交认证数
                $yhNum = 0; //银行认证数

                $sqNum = 0; //申请数
                $sq0FenNum = 0; //0分申请数
                $fkNum = 0; //放款数
                $ids = ''; //渠道ID集

                foreach ($data as $k => $v) {
                    if (strtotime($v['RegTime']) >= $startTime && strtotime($v['RegTime']) < $endTime) {
                        ++$zcNum;
                        $ids = $v['TgadminID'].','.$ids;
                        if ($v['isID'] == 1 || $v['isID'] == 2) {
                            ++$sfNum;
                        }
                        if ($v['isMobile'] == 1 || $v['isMobile'] == 2) {
                            ++$sjNum;
                        }
                        if ($v['isSocial'] == 1 || $v['isSocial'] == 2) {
                            ++$sjNums;
                        }
                        if ($v['isBank'] == 1 || $v['isBank'] == 2) {
                            ++$yhNum;
                        }
                        if ($v['AID']) {
                            ++$sqNum;
                            if ($v['LoanStatus'] == 2 || $v['LoanStatus'] == 6) {
                                ++$fkNum;
                            }
                        }
                        //如果有订单并且机审分为0
                        if($v['OrderSn'] && $v['jishen'] == 0){
                            ++$sq0FenNum;
                        }
                    }
                }

                //检测0分率是否超过15% 超过给字体标红 低于15%标绿
                $sq0FenLv = (($sqNum != 0) ? (sprintf('%.2f', ($sq0FenNum / $sqNum) * 100)) : 0);
                if($sq0FenLv > 15){
                    $sq0FenLv = '<span style="color:red;">'.$sq0FenLv.'%</span>';
                }else{
                    $sq0FenLv = '<span style="color:#00B050;">'.$sq0FenLv.'%</span>';
                }

                //检测申请率超过70% 超过给字体标红 低于40%标绿
                $sqLv = (($zcNum != 0) ? (sprintf('%.2f', ($sqNum / $zcNum) * 100)) : 0);
                if($sqLv > 75){
                    $sqLv = '<span style="color:red;">'.$sqLv.'%</span>';
                }elseif($sqLv < 40){
                    $sqLv = '<span style="color:#00B050;">'.$sqLv.'%</span>';
                }else{
                    $sqLv = $sqLv.'%';
                }

                $tempData[] = [
                    'time' => $timeArr[$i],
                    'ids' => implode(',', array_unique(explode(',', rtrim($ids, ',')))),

                    'zcNum' => $zcNum,
                    'sfNum' => $sfNum,
                    'sjNum' => $sjNum,
                    'sjNums' => $sjNums,
                    'yhNum' => $yhNum,

                    'sqNum' => $sqNum,
                    'sqLv' => $sqLv, //申请率

                    'sq0FenNum' => $sq0FenNum, //0分申请数（订单风控分）
                    'sq0FenLv' => $sq0FenLv, //0分率（订单风控分）

                    'fkNum' => $fkNum,
                    'fkLv' => (($zcNum != 0) ? (sprintf('%.2f', ($fkNum / $zcNum) * 100)) : 0).'%', //放款率
                ];
            }

            $count = count($timeData);

            return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
        }

        //获取所有渠道数据
        $data = db('tg_admin')->field('ID,Name')->select();
        $this->assign('data', $data);

        return view();
    }

    /**
     * 渠道统计 - 当天.
     */
    public function sameDay()
    {
        if (request()->isAjax()) {
            //接收参数并获取对应的用户与订单等数据
            $time = ['between', input('time').','.input('time').' 23:59:59'];
            $ids = input('ids');

            $where['m.TgadminID'] = ['in', $ids];
            $where['m.RegTime'] = $time;
            $data = db('mem_info')->alias('m')
                ->join('xb_loans_applylist a', 'm.ID = a.UserID', 'LEFT')
                ->join('xb_tg_admin t', 'm.TgadminID = t.ID', 'LEFT')
                ->where($where)
                ->group('m.ID')
                ->field('m.ID,m.isID,m.isMobile,m.isSocial,m.isBank,m.RegTime,a.ID as AID,a.LoanStatus,a.ApplyTime,t.Name,a.jishen,a.OrderSn')
                ->select();

            //处理渠道信息
            $channel = [];
            foreach (array_column($data, 'Name') as $K => $v) {
                if (!in_array($v, $channel)) {
                    array_push($channel, $v);
                }
            }

            $tempData = [];
            for ($i = 0; $i < count($channel); ++$i) {
                $zcNum = 0; //注册人数
                $sfNum = 0; //身份认证数
                $sjNum = 0; //手机认证数
                $sjNums = 0; //社交认证数
                $yhNum = 0; //银行认证数

                $sqNum = 0; //申请数
                $sq0FenNum = 0; //0分申请数
                $fkNum = 0; //放款数

                foreach ($data as $k => $v) {
                    if ($channel[$i] == $v['Name']) {
                        ++$zcNum;
                        if ($v['isID'] == 1 || $v['isID'] == 2) {
                            ++$sfNum;
                        }
                        if ($v['isMobile'] == 1 || $v['isMobile'] == 2) {
                            ++$sjNum;
                        }
                        if ($v['isSocial'] == 1 || $v['isSocial'] == 2) {
                            ++$sjNums;
                        }
                        if ($v['isBank'] == 1 || $v['isBank'] == 2) {
                            ++$yhNum;
                        }
                        if ($v['AID']) {
                            ++$sqNum;
                            if ($v['LoanStatus'] == 2 || $v['LoanStatus'] == 6) {
                                ++$fkNum;
                            }
                        }
                        //如果有订单并且机审分为0
                        if($v['OrderSn'] && $v['jishen'] == 0){
                            ++$sq0FenNum;
                        }
                    }
                }

                //检测0分率是否超过15% 超过给字体标红 低于15%标绿
                $sq0FenLv = (($sqNum != 0) ? (sprintf('%.2f', ($sq0FenNum / $sqNum) * 100)) : 0);
                if($sq0FenLv > 15){
                    $sq0FenLv = '<span style="color:red;">'.$sq0FenLv.'%</span>';
                }else{
                    $sq0FenLv = '<span style="color:#00B050;">'.$sq0FenLv.'%</span>';
                }

                //检测申请率超过70% 超过给字体标红 低于40%标绿
                $sqLv = (($zcNum != 0) ? (sprintf('%.2f', ($sqNum / $zcNum) * 100)) : 0);
                if($sqLv > 75){
                    $sqLv = '<span style="color:red;">'.$sqLv.'%</span>';
                }elseif($sqLv < 40){
                    $sqLv = '<span style="color:#00B050;">'.$sqLv.'%</span>';
                }else{
                    $sqLv = $sqLv.'%';
                }

                $tempData[] = [
                    'name' => $channel[$i],

                    'zcNum' => $zcNum,
                    'sfNum' => $sfNum,
                    'sjNum' => $sjNum,
                    'sjNums' => $sjNums,
                    'yhNum' => $yhNum,

                    'sqNum' => $sqNum,

                    'sq0FenNum' => $sq0FenNum, //0分申请数（订单风控分）
                    'sq0FenLv' => $sq0FenLv, //0分率（订单风控分）

                    'sqLv' => $sqLv, //申请率
                    'fkNum' => $fkNum,
                    'fkLv' => (($zcNum != 0) ? (sprintf('%.2f', ($fkNum / $zcNum) * 100)) : 0).'%', //放款率
                ];
            }
            //总条数
            $count = count($channel);

            return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $tempData]);
        }

        $this->assign('time', input('time'));
        $this->assign('ids', input('ids'));

        return view();
    }

    /**
     * 获取时间参数.
     *
     * @param int    $page  请求页数
     * @param int    $limit 请求条数
     * @param string $time  请求时间
     *
     * @return array
     */
    private function getTimeData($page, $limit, $time = '')
    {
        //时间
        if ($time != '') {
            $time = explode(' - ', $time);
            $days = diffBetweenTwoDays($time[0], $time[1]);
        } else {
            $days = '-1';
        }

        $dayMax = ($days == '-1') ? $limit : $days;

        $timeData = [];
        for ($i = 0; $i <= $dayMax; ++$i) {
            $timeData[] = (isset($time[1])) ? (date('Y-m-d', strtotime("{$time[1]} -{$i} day"))) : date('Y-m-d', strtotime("-{$i} day"));
        }

        return $timeData;
    }
}
